package com.ll.domain.wechat.base;

import com.alibaba.fastjson.JSONObject;
import com.ll.app.api.req.WechatUserLoginDTO;
import com.ll.base.util.HttpUtil;
import com.ll.domain.tenant.enums.SystemOSEnum;
import com.ll.domain.user.dto.UserLoginDTO;
import com.ll.domain.wechat.constant.WechatConstant;

public class WechatBaseService {
    private static  HttpUtil httpUtil = new HttpUtil();
    private static String appid = "wxba61ec74eb5a8e2e";
    private static String secret = "41043c68e4eb81486c3a7e7d063cbf59";

    public static UserLoginDTO wechatLogin(WechatUserLoginDTO loginDTO){
        String accessToken = getAccessToken();
        String openUid = getUid(loginDTO.getLoginCode());
        return UserLoginDTO.builder()
                .tenantId(loginDTO.getTenantId())
                .app(loginDTO.getApp())
                .os(SystemOSEnum.微信小程序)
                .otherToken(accessToken)
                .otherUserId(openUid)
                .build();
    }

    public static String getUid(String jsCode){
        String url = WechatConstant.GET_UID + "?appid="+appid+"&secret="+secret+"&js_code="+jsCode+"&grant_type=authorization_code";
        String resp = httpUtil.doGet(url);
        System.out.println(resp);
        return JSONObject.parseObject(resp).getString("openid");
    }

    public static String getAccessToken(){
        String url = WechatConstant.GET_TOKEN + "?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String resp = httpUtil.doGet(url);
        return JSONObject.parseObject(resp).getString("access_token");
    }

}
